﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 扩展整体文本间距，可以指定字符下标不参与间距，用于插入特殊字符或图像
    /// </summary>
    [RequireComponent(typeof(Text))]
    [AddComponentMenu("Nirvana/UI/Effects/Text Expand")]
    public class UITextExpand : BaseMeshEffect
    {
        private const int defaultCount = 6;
        [SerializeField]
        private float fitWidth = -1f;//扩展宽度，默认-1，则以rect宽度扩展字符间隔，不然则必须大于 count * fontsize宽度扩展间距
        [SerializeField]
        private int[] skips; //设置指定字符下标不扩展宽度间隔

        public override void ModifyMesh(VertexHelper vh)
        {
            if (!this.IsActive() || vh.currentVertCount <= 0)
            {
                return;
            }
            Text txt = GetComponent<Text>();
            if(txt == null)
            {
                Debug.LogWarning("LetterSpacing: Missing Text component");
                return;
            }
            RectTransform rectTransform = this.transform as RectTransform;
            if (rectTransform == null)
            {
                Debug.LogWarning("LetterSpacing: Missing RectTransform component");
                return;
            }
            float width = -1;
            if(this.fitWidth > 0)
            {
                width = this.fitWidth - txt.preferredWidth;
            }
            else
            {
                width = rectTransform.rect.width - txt.preferredWidth;
            }
      
            if (width < 0) return;
            int length = 0;
            if (this.skips != null) length = this.skips.Length;
            int index = txt.text.Length - 1 - length;
            if (index <= 0) return;
            float fontsize = width / index / txt.fontSize;

            List<UIVertex> tempList = VertexLists.Get();
            vh.GetUIVertexStream(tempList);
            List<UIVertex> newlist = ModifyText(tempList,txt,fontsize);
            if (newlist != null)
            {
                vh.Clear();
                vh.AddUIVertexTriangleStream(newlist);
            }
            VertexLists.Set(newlist);
        }

        private List<UIVertex> ModifyText(List<UIVertex>_list,Text txt,float width)
        {
            float num = 0;
            switch (txt.alignment)
            {
                case TextAnchor.UpperLeft:
                case TextAnchor.MiddleLeft:
                case TextAnchor.LowerLeft:
                    num = 0;
                    break;
                case TextAnchor.UpperCenter:
                case TextAnchor.MiddleCenter:
                case TextAnchor.LowerCenter:
                    num = 0.5f;
                    break;
                case TextAnchor.UpperRight:
                case TextAnchor.MiddleRight:
                case TextAnchor.LowerRight:
                    num = 1;
                    break;
            }

            UIVertex[] vertexs = new UIVertex[6];
            int[] temparray = new int[6];
            int count = 0;
            string[] txts = txt.text.Split(new char[] { '\n' });
            float totalwidth = width * (float)txt.fontSize;
            foreach(var s in txts)
            {
                float w = (s.Length - 1) * totalwidth * num;
                int n = 0;
                for(int i = 0; i < s.Length; i++)
                {
                    for(int k = 0; k < 6; k++)
                    {
                        temparray[k] = count * 6 + k;
                    }

                    if (temparray[temparray.Length - 1] > _list.Count - 1) return null;
                    for(int l = 0; l < 6; l++)
                    {
                        vertexs[l] = _list[temparray[l]];
                    }
                    Vector3 vector = Vector3.right * (totalwidth * n - w);
                    if (!IsSkips(i, s.Length))
                    {
                        n++;
                    }
                    for(int j = 0; j < 6; j++)
                    {
                        vertexs[j].position = vertexs[j].position + vector;
                    }

                    for(int j = 0; j < 6; j++)
                    {
                        _list[temparray[j]] = vertexs[j];
                    }
                    count++;
                }
                count++;
            }
            return _list;
        }

        private bool IsSkips(int index,int length)
        {
            if(this.skips == null)
            {
                return false;
            }

            foreach(var v in this.skips)
            {
                if(v >= 0)
                {
                    if (index == v) return true;
                }else if(index == length - 1 + v)
                {
                    return true;
                }
            }
            return false;

        }







    }
}

